package logic

import (
	"context"
	"fmt"
	"ho/models/cache"
	"ho/models/mysql"

	"ho/horpc/horpc"
	"ho/horpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *horpc.LoginRequest) (*horpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	res, _ := cache.RDB.Get(l.ctx, "sendSms"+in.Phone).Result()
	if res != in.SendSmsCode {
		return nil, fmt.Errorf("验证码错误，请重新输入")
	}

	var user mysql.User
	mysql.DB.Debug().Where("phone=?", in.Phone).Find(&user)
	if user.ID == 0 {
		user = mysql.User{
			Phone:    in.Phone,
			Password: in.Password,
		}
		mysql.DB.Debug().Create(&user)
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}
	return &horpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
